package com.hxc.shop.config.interceptors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * PC端登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // System.out.println("前置方法执行..");

//        logger.info("进入LoginInterceptor拦截器---------------------------------------");
//        final String empNo = request.getParameter("cacheKeyValue");
//        if (StringUtils.isBlank(empNo)) {
//            //放行
//            return true;
//        }
//        logger.info("登录人账号:{}", empNo);
//
//        //IP
//        String ipStr = request.getHeader("x-forwarded-for");
//        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
//            ipStr = request.getHeader("Proxy-Client-IP");
//        }
//        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
//            ipStr = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
//            ipStr = request.getRemoteAddr();
//        }
//
//        ipStr = ipStr.replace(".", "");
//        logger.info("登录人ip:{}", ipStr);
//
//        //当前有效登录人账号
//        final String val = (String) CacheUtils.get(ipStr);
//        logger.info("当前有效登录人账号:{}", val);
//
//        if (StringUtils.isBlank(val)) {
//            CacheUtils.put(ipStr, empNo);
//        } else {
//            if (!empNo.equals(val)) {
//                response.addHeader("redirectUrl", "https://localhost:9001/#/login");
//                return false;
//            }
//        }

        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // System.out.println("后置方法执行..");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // System.out.println("完成方法执行..");
    }
}
